package com.huiyan.hysys.service.impl;

import com.huiyan.hysys.bo.SmsCodeBo;
import com.huiyan.hysys.config.RedisKeyConfig;
import com.huiyan.hysys.config.SystemConfig;
import com.huiyan.hysys.dao.SmsLogDao;
import com.huiyan.hysys.entity.SmsLog;
import com.huiyan.hysys.service.intf.SmsService;
import com.huiyan.hysys.third.AliSmsUtil;
import com.huiyan.hysys.third.JedisUtil;
import com.huiyan.hysys.util.NumUtil;
import com.huiyan.hysys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsLogDao dao;


    @Override
    public R sendCode(String phone) {
        //生成验证码
        String key = RedisKeyConfig.CODE_R + phone;
        int code;
        //校验key
        if (JedisUtil.checkKey(key)){
            //验证时间
            if (JedisUtil.ttl(key)>RedisKeyConfig.CODE_R_TIME/2){
                code = Integer.parseInt(JedisUtil.getStr(key));
            }else{
                code= NumUtil.createNum(SystemConfig.CODE_LEN);
            }
        }else{
            code= NumUtil.createNum(SystemConfig.CODE_LEN);
        }

        //2.发送短信
        if(AliSmsUtil.sendRegisterCode(phone,code)){
            //3.记录验证码 --Redis  有效期
            JedisUtil.addStr(key,code+"",RedisKeyConfig.CODE_R_TIME);
            //4.更新数据库
            dao.insert(new SmsLog(SystemConfig.SMS_TYPE_1,"注册账号",phone,new Date()));
            //5.返回
            return R.ok();
        }
        return R.fail();

    }

    @Override
    public R sendLoginCode(String phone) {
        //1.生成验证码
        String key=RedisKeyConfig.CODE_L+phone;
        int code;
        //校验key
        if(JedisUtil.checkKey(key)){
            //验证时间
            if(JedisUtil.ttl(key)>RedisKeyConfig.CODE_R_TIME/2){
                code=Integer.parseInt(JedisUtil.getStr(key));
            }else {
                code= NumUtil.createNum(SystemConfig.CODE_LEN);
            }
        }else {
            code= NumUtil.createNum(SystemConfig.CODE_LEN);
        }
        //2.发送短信
        if(AliSmsUtil.sendRegisterCode(phone,code)){
            //3.记录验证码 --Redis  有效期
            JedisUtil.addStr(key,code+"",RedisKeyConfig.CODE_R_TIME);
            //4.更新数据库
            dao.insert(new SmsLog(SystemConfig.SMS_TYPE_2,"登陆账号",phone,new Date()));
            //5.返回
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R checkCode(SmsCodeBo bo) {
        String key=RedisKeyConfig.CODE_R+bo.getPhone();
        //校验是否存在
        if(JedisUtil.checkKey(key)){
            //校验验证码是否正确
            if(bo.getCode()==Integer.parseInt(JedisUtil.getStr(key))){
                //删除验证码 一次性有效
                JedisUtil.delKey(key);
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R all() {
        return R.ok(dao.selectList(null));
    }
}
